package com.lhkj.ct.base.utils;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import org.apache.commons.lang3.StringUtils;

import java.beans.Introspector;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;

/**
 * @Description : lambda工具类
 */
public final class LambdaUtils{

    public static <T> String getName(SFunction<T, ?> fn) {
        return getName(fn, null);
    }

    public static <T> String getName(SFunction<T, ?> fn, String alias) {
        try {
            Method method = fn.getClass().getDeclaredMethod("writeReplace");
            boolean accessible = method.isAccessible();
            method.setAccessible(Boolean.TRUE);
            SerializedLambda serializedLambda = (SerializedLambda) method.invoke(fn);
            method.setAccessible(accessible);
            String getter = serializedLambda.getImplMethodName();
            String fieldName = Introspector.decapitalize(getter.replace("get", ""));
            return StringUtils.isNotBlank(alias) ? (alias + "." + fieldName) : fieldName;
        } catch (ReflectiveOperationException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> String getUnderLineName(SFunction<T, ?> fn) {
        return StrUtil.toUnderlineCase(getName(fn));
    }

    /**
     * 获取下划线名称
     */
    public static <T> String getUnderLineName(SFunction<T, ?> fn, String alias) {
        String underLineName = getUnderLineName(fn);
        return StringUtils.isNotBlank(alias) ? (alias + "." + underLineName) : underLineName;
    }

}
